<?php


namespace app\api\model\mysql;


use app\common\model\TimeModel;
use think\Exception;

class MallAccountLog extends TimeModel
{
    /**
     * 记录钱包明细
     * @param string $openid
     * @param float $money
     * @param int $changType
     * @param string $changedesc
     * @return bool
     */
    public function saveAccoutLog(int $order_id=0,string $openid,float $money,int $changType=1,string $changedesc='分享返利'){

        $member =(new MallUser())->getUserByList($openid);
        // 3 分享  4平台增加
        if($changType>2){
            switch ($changType){
                case 3:
                    $balance =round($member['balance']+$money,2);
                    break;
                case 4:
                    $balance =round($member['againbalance']+$money,2);
                    break;
                case 5:
                    $balance =round($member['teambalance']+$money,2);
                    break;
                default:
                    $balance =round($member['balance']+$money,2);
                    break;
            }

        }else{ // 0 平台减少 1余额支付 2提现
            $balance =round($member['balance']-$money,2);
        }

        if($balance < 0){
            throw new Exception('余额不足');
        }
        $data=array(
            'money' =>$money,
            'openid'=>$openid,
            'mid'  =>$member['id'],
            'order_id'=>$order_id,
            'change_type'=>$changType,
            'istx' =>0,
            'change_date'=>date('Y-m-d'),
            'change_desc'=>$changedesc
        );
        try{
            $this->save($data);
            switch ($changType){
                case 3:
                    $member->save(array('balance'=>$balance));
                    break;
                case 4:
                    $member->save(array('againbalance'=>$balance));
                    break;
                case 5:
                    $member->save(array('teambalance'=>$balance));
                    break;
                default:
                    $member->save(array('balance'=>$balance));
                    break;
            }
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
        return true;
    }

}